import logging
import json
import yaml
import requests


def login_keep_token(env):
    # 读取配置文件
    with open('../apiSecurity/data/config/config.yaml', 'r') as f:
        config = yaml.safe_load(f)

    # 获取配置参数
    url = config['environments'][env]['uri']
    admin_name = config['environments'][env]['adminName']
    admin_password = config['environments'][env]['adminPassword']

    # 构造请求体
    payload = {
        'name': admin_name,
        'password': admin_password,
        'publicKeyId': 0
    }
    data = json.dumps(payload)
    # print(data)
    # 发送请求
    response = requests.post(url, data=data, headers={'Content-Type': 'application/json', 'version': '2.0', 'X-Encrypt-Key': 'xiOqLGgy6JV1Ggs+dKc+TU/Mo/wTA8CFT5B16fRQZU8WIvtRulI0j6A204S66i5fJlksnltuVwv1WQdlKeITkx0VN/g82dn9L8s7jESTX4VfI3U31/Z/fXPhvH9j+og0jOCapYXeNZL7tQ18fXtZr2BLcjCo/Yv4X0An6Ql5C60='})
    # print(response.text)
    # 解析响应体，提取token的值
    response_json = response.json()
    if response_json.get('code') != '200':
        logging.info("失败----未能成功获取token")
        raise Exception(f"失败----未能成功获取token，响应信息：{response.text}")
    token = response_json.get('data', {}).get('token')
    # print(token)
    # 将token写入yml文件
    with open('../apiSecurity/data/config/token.yml', 'w') as f:
        yaml.safe_dump({'token': token}, f)
    logging.info("成功----已提取到token")
